<template>
  <el-card ref="wrapper" :body-style="{ padding: 0 }">
    <v-stage :config="stageConfig" @mousedown="mousedownHandler" @mouseup="mouseupHandler" @mousemove="mousemoveHandler">
      <v-layer>
        <v-line v-for="(line, index) in lines" :key="index" :config="line"></v-line>
      </v-layer>
    </v-stage>
  </el-card>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
export default {
  data() {
    return {
      // 画布配置
      stageConfig: {
        width: 800,
        height: 700
      },
      stroke: '#df4b26',
      strokeWidth: 5,
      // 绘画状态
      painting: false,
    }
  },
  computed: {
    ...mapState(['lines']),
    ...mapGetters(['isGameStarted', 'isGameHolder'])
  },
  mounted() {
    // 将画布宽度设置与容器同宽
    this.stageConfig.width = this.$refs.wrapper.$el.offsetWidth
  },
  methods: {
    // 鼠标按下，只有游戏开始了，且是主持人，才能绘画
    mousedownHandler(e) {
      if (!this.isGameStarted || !this.isGameHolder) return
      this.painting = true
      // 创建一个新线条
      const newLine = {
        stroke: this.stroke,
        strokeWidth: this.strokeWidth,
        points: [e.evt.layerX, e.evt.layerY]
      }
      this.$store.commit('drawNewLine', newLine)
      this.$store.dispatch('sendDrawNewLine', newLine)
    },
    // 鼠标拖动
    mousemoveHandler(e) {
      if (this.painting) {
        let lastLine = this.lines.at(-1)
        // concat增加数据到新数组，不会更改原数组
        lastLine.points = lastLine.points.concat([e.evt.layerX, e.evt.layerY])
        this.$store.commit('updateNewLine', lastLine)
        this.$store.dispatch('sendUpdateDrawNewLine', lastLine)
      }
    },
    // 鼠标释放
    mouseupHandler() {
      this.painting = false
    }
  }
}
</script>
